﻿using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Collections;
using System.Reflection;
using ReadWriteFiles;
using System.Data;
using System.Diagnostics;

namespace Negocio
{
    public class Club
    {

        private ObservableCollection<Group> groups;
        private ObservableCollection<Player> players;
        private ObservableCollection<Appointment> appointments;
        private ObservableCollection<Activity> activities;
        private ObservableCollection<Evaluation> evaluations;
        private ObservableCollection<PlayerExecution> playersExecutions;
        private ObservableCollection<Test> tests;
        private ObservableCollection<ClinicalHistory> clinicalHistories;
        private ObservableCollection<Disease> diseases;
        private ObservableCollection<Injury> injuries;
        private IPersistence iPersist;
        private static IPersistence iPers;
        public static Club instance;



        public Club()
        {
            groups = new ObservableCollection<Group>();
            players = new ObservableCollection<Player>();
            appointments = new ObservableCollection<Appointment>();
            activities = new ObservableCollection<Activity>();
            evaluations = new ObservableCollection<Evaluation>();
            playersExecutions = new ObservableCollection<PlayerExecution>();
            tests = new ObservableCollection<Test>();
            clinicalHistories = new ObservableCollection<ClinicalHistory>();
            diseases = new ObservableCollection<Disease>();
            injuries = new ObservableCollection<Injury>();
            reflectionGetPersistence(System.IO.Directory.GetCurrentDirectory());
        }



        public static Club getInstance()
        {
            if (instance == null)
            {
                instance = new Club();
            }
            return instance;
        }

        public static IPersistence getPersistence()
        {
            return iPers;
        }

        public ObservableCollection<Group> Groups
        {
            get { return this.groups; }
        }

        public ObservableCollection<Player> Players
        {
            get { return this.players; }
            set { this.players = value; }
        }

        public ObservableCollection<Appointment> Appointments
        {
            get { return this.appointments; }
        }

        public IList<Activity> Activities
        {
            get { return this.activities; }
        }

        public ObservableCollection<Evaluation> Evaluations
        {
            get { return this.evaluations; }
        }

        public ObservableCollection<PlayerExecution> PlayersExecutions
        {
            get { return this.playersExecutions; }
        }

        public ObservableCollection<Test> Tests
        {
            get { return this.tests; }
        }

        public ObservableCollection<ClinicalHistory> ClinicalHistories 
        {
            get { return this.clinicalHistories; }
            set { this.clinicalHistories = value; }
        }

        public ObservableCollection<Disease> Diseases 
        {
            get { return this.diseases; }
            set { this.diseases = value; }
        }

        public IPersistence IPersist
        {
            get { return this.iPersist; }
            set { this.iPersist = value; }
        }

        public bool addGroup(Group oneGroup)
        {
            bool ret = false;
            if (!this.Groups.Contains(oneGroup))
            {
                this.Groups.Add(oneGroup);
                ret = true;
                oneGroup.added();
            }
            return ret;
        }

        public void removeGroup(Group oneGroup)
        {
            this.Groups.Remove(oneGroup);
            oneGroup.removed();
        }

        public void removeGroup(int position)
        {
            Group removedGroup = this.Groups[position];
            removedGroup.removed();
            this.Groups.RemoveAt(position);
        }

        public bool addPlayer(Player onePlayer)
        {
            bool ret = false;
            if (!this.Players.Contains(onePlayer))
            {
                this.Players.Add(onePlayer);
                ret = true;
                onePlayer.added();
                ClinicalHistory clinicalHistory = new ClinicalHistory();
                clinicalHistoryData(onePlayer, clinicalHistory);
                clinicalHistory.added();
            }
            return ret;
        }

        public void removePlayer(Player onePlayer)
        {
            this.Players.Remove(onePlayer);
        }

        public bool addAppointment(Appointment oneAppointment)
        {
            bool ret = false;
            if (!this.Appointments.Contains(oneAppointment))
            {
                this.Appointments.Add(oneAppointment);
                ret = true;
            }
            return ret;
        }

        public void removeAppointment(Appointment oneAppointment)
        {
            this.Appointments.Remove(oneAppointment);
        }

        public bool addActivity(Activity oneActivity)
        {
            bool ret = false;
            if (!this.Activities.Contains(oneActivity))
            {
                this.Activities.Add(oneActivity);
                ret = true;
            }
            return ret;
        }

        public void removeActivity(Activity oneActivity)
        {
            this.Activities.Remove(oneActivity);
        }

        public bool addEvaluation(Evaluation oneEvaluation)
        {
            bool ret = false;
            if (!this.Evaluations.Contains(oneEvaluation))
            {
                this.Evaluations.Add(oneEvaluation);
                ret = true;
                oneEvaluation.added();
            }
            return ret;
        }

        public void removeEvaluation(Evaluation oneEvaluation)
        {
            this.Evaluations.Remove(oneEvaluation);
            oneEvaluation.removed();
        }

        public bool addPlayerExecution(PlayerExecution onePlayerExecution)
        {
            bool ret = false;
            if (!this.PlayersExecutions.Contains(onePlayerExecution))
            {
                this.PlayersExecutions.Add(onePlayerExecution);
                ret = true;
                onePlayerExecution.added();
            }
            return ret;
        }

        public void removePlayerExecution(PlayerExecution onePlayerExecution)
        {
            this.PlayersExecutions.Remove(onePlayerExecution);
        }

        public bool addTest(Test oneTest)
        {
            bool ret = false;
            if (!this.Tests.Contains(oneTest))
            {
                this.Tests.Add(oneTest);
                ret = true;
            }
            return ret;
        }

        public void removeTest(Test oneTest)
        {
            this.Tests.Remove(oneTest);
        }

        public bool addClinicalHistory(ClinicalHistory clinicalHistory)
        {
            bool ret = false;
            if (!this.clinicalHistories.Contains(clinicalHistory))
            {
                this.clinicalHistories.Add(clinicalHistory);
                ret = true;
                clinicalHistory.added();
            }
            return ret;
        }        

        public void removeClinicalHistory(int position)
        {
            ClinicalHistory clinicalHisory = this.clinicalHistories[position];
            clinicalHisory.removed();
            this.clinicalHistories.RemoveAt(position);
        }

        public bool addDisease(Disease disease)
        {
            bool ret = false;
            if (!this.diseases.Contains(disease))
            {
                this.diseases.Add(disease);
                ret = true;
                disease.added();
            }
            return ret;
        }

        public void removeDisease(int position)
        {
            Disease disease = this.diseases[position];
            disease.removed();
            this.diseases.RemoveAt(position);
        }

        public bool addInjury(Injury injury)
        {
            bool ret = false;
            if (!this.injuries.Contains(injury))
            {
                this.injuries.Add(injury);
                ret = true;
                injury.added();
            }
            return ret;
        }

        public void removeInjury(int position)
        {
            Injury injury = this.injuries[position];
            injury.removed();
            this.injuries.RemoveAt(position);
        }

        public void loadPlayers()
        {
            if (this.Players.Count == 0)
            {
                ObservableCollection<object> objectList = this.IPersist.bringList(new Player());
                for (int i = 0; i < objectList.Count; i++)
                {
                    this.Players.Add((Player)objectList[i]);
                }
            }            
        }

        public void loadGroups()
        {
            if (this.Groups.Count == 0)
            {
                ObservableCollection<object> objectList = this.IPersist.bringList(new Group());
                for (int i = 0; i < objectList.Count; i++)
                {
                    Group group = (Group)objectList[i];
                    this.Groups.Add(group);
                    for (int j = 0; j < group.Players.Count; j++)
                    {
                        for (int k = 0; k < this.Players.Count; k++)
                        {
                            if (group.Players[j].OID == this.Players[k].OID)
                            {
                                group.Players[j] = this.Players[k];
                                k = this.Players.Count;
                            }
                        }
                    }
                }
            }

        }

        public void loadAppointments()
        {
            if (this.Appointments.Count == 0)
            {
                ObservableCollection<object> objectList = this.IPersist.bringList(new Appointment());
                for (int i = 0; i < objectList.Count; i++)
                {
                    this.Appointments.Add((Appointment)objectList[i]);
                }
            }
        }

        public void loadActivities()
        {
            if (this.Activities.Count == 0)
            {
                ObservableCollection<object> objectList = this.IPersist.bringList(new Activity());
                for (int i = 0; i < objectList.Count; i++)
                {
                    this.Activities.Add((Activity)objectList[i]);
                }
            }
        }

        public void loadEvaluations()
        {
            if (Evaluations.Count == 0)
            {
                ObservableCollection<object> objectList = this.IPersist.bringList(new Evaluation());
                for (int i = 0; i < objectList.Count; i++)
                {
                    Evaluation evaluation = (Evaluation)objectList[i];
                    this.Evaluations.Add((Evaluation)objectList[i]);
                    for (int j = 0; j < evaluation.Tests.Count; j++)
                    {
                        for (int k = 0; k < this.Tests.Count; k++)
                        {
                            if (evaluation.Tests[j].OID == this.Tests[k].OID)
                            {
                                evaluation.Tests[j] = this.Tests[k];
                                k = this.Tests.Count;
                            }
                        }
                    }
                }
            }
        }

        public void loadPlayersExecutions()
        {
            if (this.playersExecutions.Count == 0)
            {
                ObservableCollection<object> objectList = this.IPersist.bringList(new PlayerExecution());
                for (int i = 0; i < objectList.Count; i++)
                {
                    this.PlayersExecutions.Add((PlayerExecution)objectList[i]);
                    for (int j = 0; j < this.Players.Count; j++)
                    {
                        if (((PlayerExecution)objectList[i]).Player.OID == this.Players[j].OID)
                        {
                            ((PlayerExecution)objectList[i]).Player = this.Players[j];
                            j = this.Players.Count;
                        }
                    }
                    for (int j = 0; j < ((PlayerExecution)objectList[i]).Values.Count; j++)
                    {
                        for (int k = 0; k < this.Tests.Count; k++)
                        {
                            if (((PlayerExecution)objectList[i]).Values[j].Test.OID == this.Tests[k].OID)
                            {
                                ((PlayerExecution)objectList[i]).Values[j].Test = this.Tests[k];
                            }
                        }
                    }
                }
            }
        }

        public void loadTests()
        {
            if (this.Tests.Count == 0)
            {
                ObservableCollection<object> objectList = this.IPersist.bringList(new Test());
                this.Tests.Clear();
                for (int i = 0; i < objectList.Count; i++)
                {
                    this.Tests.Add((Test)objectList[i]);
                }
            }
        }

        public void loadClinicalHistories()
        {
            if (this.ClinicalHistories.Count == 0)
            {
                ObservableCollection<object> objectList = this.IPersist.bringList(new ClinicalHistory());
                for (int i = 0; i < objectList.Count; i++)
                {
                    this.clinicalHistories.Add((ClinicalHistory)objectList[i]);
                }
            }
        }

        public ObservableCollection<PlayerExecution> loadPlayersExecutionByDate(DateTime date, string evaluationGroupNames)
        {
            ObservableCollection<PlayerExecution> dateExecutions = new ObservableCollection<PlayerExecution>();
            evaluationGroupNames = evaluationGroupNames.Trim();
            string[] names = evaluationGroupNames.Split(',');
            for (int i = 0; i < this.PlayersExecutions.Count; i++)
            {
                if (this.PlayersExecutions[i].Date.ToShortDateString().Equals(date.ToShortDateString()) && this.PlayersExecutions[i].EvaluationName.Equals(names[0]) && this.PlayersExecutions[i].GroupName.Equals(names[1].Trim()))
                {
                    dateExecutions.Add(PlayersExecutions[i]);
                }
            }
            return dateExecutions;
        }

        public ObservableCollection<PlayerExecution> loadPlayerExecutionsBetweenDates(DateTime begginingDate, DateTime endDate, string playerID, string evaluationName)
        {
            ObservableCollection<PlayerExecution> playerExecutions = new ObservableCollection<PlayerExecution>();
            for (int i = 0; i < this.playersExecutions.Count; i++)
            {
                if ((this.PlayersExecutions[i].Date >= begginingDate) && (this.PlayersExecutions[i].Date <= endDate) && (this.PlayersExecutions[i].Player.IdentityDocument.Equals(playerID)) && (this.PlayersExecutions[i].EvaluationName.Equals(evaluationName)))
                {
                    playerExecutions.Add(this.PlayersExecutions[i]);
                }
            }            
            return playerExecutions;
        }


        public ObservableCollection<Player> loadEnabledPlayers()
        {
            ObservableCollection<Player> enabledPlayers = new ObservableCollection<Player>();
            for (int i = 0; i < this.Players.Count; i++)
            {
                if (this.Players[i].Enabled)
                {
                    enabledPlayers.Add(this.Players[i]);
                }
            }
            return enabledPlayers;
        }

        public ObservableCollection<Player> loadDisabledPlayers()
        {
            ObservableCollection<Player> disabledPlayers = new ObservableCollection<Player>();
            for (int i = 0; i < this.Players.Count; i++)
            {
                if (!this.Players[i].Enabled)
                {
                    disabledPlayers.Add(this.Players[i]);
                }
            }
            return disabledPlayers;
        }

        public ObservableCollection<string> loadEvaluationWithGroup(DateTime date)
        {
            return this.IPersist.loadEvaluationWithGroup(date);
        }

        public Player playerByName(string name)
        {
            Player player = new Player();
            bool foundPlayer = false;
            for (int i = 0; i < this.Players.Count && !foundPlayer; i++)
            {
                if (this.Players[i].CompleteName.Equals(name))
                {
                    foundPlayer = true;
                    player = this.Players[i];
                }
            }
            return player;
        }

        public Test testByName(string name)
        {
            Test test = new Test();
            bool foundTest = false;
            for (int i = 0; i < this.Tests.Count && !foundTest; i++)
            {
                if (this.Tests[i].Name.Equals(name))
                {
                    foundTest = true;
                    test = this.Tests[i];
                }
            }
            return test;
        }

        public ClinicalHistory getClinicalHistory(Player player)
        {
            ClinicalHistory clinical = null;
            for (int i = 0; i < clinicalHistories.Count; i++)
            {
                clinical = clinicalHistories[i];
                if (clinical.Player.OID == player.OID)
                {
                    clinical.Player = player;
                    i = clinicalHistories.Count;
                }
            }
            return clinical;
        }

        public bool addReferenceMeasureToTest(Test oneTest, ReferenceMeasure oneReference)
        {
            return oneTest.addReferenceMeasure(oneReference);
        }

        public bool addTestToEvaluation(Evaluation evaluation, Test test)
        {
            return evaluation.addTest(test);
        }

        public Player newPlayer(string name, string firstLastName, string secondLastName, string identityDocument, DateTime birthDate, DateTime admissionDate, string weight, string team, string height, bool enabled, string position, string leg, string picture)
        {
            Player player = new Player();
            player = playerData(name, firstLastName, secondLastName, identityDocument, birthDate, admissionDate, weight, team, height, enabled, position, leg, picture, player);
            return player;
        }

        public Player updatePlayer(string name, string firstLastName, string secondLastName, string identityDocument, DateTime birthDate, DateTime admissionDate, string weight, string team, string height, bool enabled, string position, string leg, string picture, Player onePlayer)
        {
            Player playerAux = new Player();
            playerAux.OID = onePlayer.OID;
            onePlayer = playerData(name, firstLastName, secondLastName, identityDocument, birthDate, admissionDate, weight, team, height, enabled, position, leg, picture, playerAux);
            if (onePlayer != null)
            {
                onePlayer.updated();
                if (!enabled)
                {
                    for (int i = 0; i < this.Groups.Count; i++)
                    {
                        if (this.Groups[i].Players.Contains(onePlayer))
                        {
                            this.Groups[i].deletePlayer(onePlayer);
                            this.Groups[i].updated();
                        }
                    }
                }
            }
            return onePlayer;
        }

        private Player playerData(string name, string firstLastName, string secondLastName, string identityDocument, DateTime birthDate, DateTime admissionDate, string weight, string team, string height, bool enabled, string position, string leg, string picture, Player player)
        {
            try
            {
                    player.Name = name;
                    player.FirstLastname = firstLastName;
                    player.SecondLastname = secondLastName;
                    player.IdentityDocument = identityDocument;
                    player.BirthDate = birthDate;
                    player.AdmissionDate = admissionDate;
                    player.Weight = float.Parse(weight);
                    player.Club = team;
                    player.Height = float.Parse(height);
                    player.Enabled = enabled;
                    player.Position = position;
                    player.Leg = leg;
                    player.Photo = picture;
            }
            catch (Exception)
            {
                player = null;
            }
            if (validatePlayerData(player))
            {
                return player;
            }
            else
            {
                return null;
            }
        }

        private bool validatePlayerData(Player player)
        {
            bool ret = false;
            if (player != null)
            {                
                if (player["Name"] == null && player["FirstLastname"] == null && player["SecondLastname"] == null && player["IdentityDocument"] == null && player["Weight"] == null && player["Height"] == null &&player["Position"]==null && player["Leg"]==null)
                {
                    ret = true;
                }
                else
                {
                    ret = false;
                }
            }            
            return ret;
        }

        public Group newGroup(string name, ObservableCollection<Player> groupPlayers)
        {
            Group group = new Group();
            group = groupData(name, groupPlayers, group);
            return group;
        }

        public Group updateGroup(string name, ObservableCollection<Player> groupPlayers, Group oneGroup)
        {
            oneGroup = groupData(name, groupPlayers, oneGroup);
            if (oneGroup != null)
            {
                oneGroup.updated();
            }
            return oneGroup;
        }

        private Group groupData(string name, ObservableCollection<Player> groupPlayers, Group group)
        {
            try
            {
                group.Name = name;
                group.Players.Clear();
                for (int i = 0; i < groupPlayers.Count; i++)
                {
                    group.addPlayer(groupPlayers[i]);
                }
            }
            catch (Exception)
            {
            }
            if (validateGroupData(group))
            {
                return group;
            }
            else
            {
                return null;
            }
        }

        private bool validateGroupData(Group group)
        {
            bool ret = true;
            if (group["Name"] == null)
            {
                ret = true;
            }
            else
            {
                ret = false;
            }
            return ret;
        }

        public Test newTest(string name, string sequence, string measureUnit, ObservableCollection<ReferenceMeasure> references)
        {
            Test test = new Test();
            test = testData(name, sequence, measureUnit, references, test);
            return test;
        }

        public Test updateTest(string name, string sequence, string measureUnit, ObservableCollection<ReferenceMeasure> references, Test oneTest)
        {
            oneTest = testData(name, sequence, measureUnit, references, oneTest);
            if (oneTest != null)
            {
                oneTest.updated();
            }
            return oneTest;
        }

        private Test testData(string name, string sequence, string measureUnit, ObservableCollection<ReferenceMeasure> references, Test test)
        {
            try
            {
                test.Name = name;
                test.Sequence = sequence;
                test.MeasureUnit = measureUnit;
                for (int i = 0; i < references.Count; i++)
                {
                    test.addReferenceMeasure(references[i]);
                }
            }
            catch (Exception)
            {
            }
            if (validateTest(test))
            {
                return test;
            }
            else
            {
                return null;
            }

        }

        private bool validateTest(Test oneTest)
        {
            bool ret;
            if (oneTest["Name"] == null)
            {
                ret = true;
            }
            else
            {
                ret = false;
            }
            return ret;
        }

        public Evaluation newEvaluation(string name, string description, ObservableCollection<Test> tests)
        {
            Evaluation evaluation = new Evaluation();
            evaluation = evaluationData(name, description, tests, evaluation);
            return evaluation;
        }

        public Evaluation updateEvaluation(string name, string description, ObservableCollection<Test> tests, Evaluation evaluation)
        {
            evaluation = evaluationData(name, description, tests, evaluation);
            if (evaluation != null)
            {
                evaluation.updated();
            }
            return evaluation;
        }

        private Evaluation evaluationData(string name, string description, ObservableCollection<Test> tests, Evaluation evaluation)
        {
            try
            {
                evaluation.Name = name;
                evaluation.Description = description;
                for (int i = 0; i < tests.Count; i++)
                {
                    evaluation.addTest(tests[i]);
                }
            }
            catch (Exception)
            {
            }
            if (validateEvaluation(evaluation))
            {
                return evaluation;
            }
            else
            {
                return null;
            }
        }

        private bool validateEvaluation(Evaluation evaluation)
        {
            bool ret;
            if (evaluation["Name"] == null)
            {
                ret = true;
            }
            else
            {
                ret = false;
            }
            return ret;
        }

        public PlayerExecution newPlayerExecution(string evaluationName, string groupName, Player player, ObservableCollection<TestValue> testValues, string comments, DateTime executionDate)
        {
            PlayerExecution pExecution = new PlayerExecution();
            pExecution = playerExecutionData(evaluationName, groupName, player, testValues, executionDate,comments, pExecution);
            return pExecution;
        }

        public PlayerExecution updatePlayerExecution(string evaluationName, string groupName, Player player, ObservableCollection<TestValue> testValues, DateTime executionDate, string comments, PlayerExecution playerExecution)
        {
            playerExecution = playerExecutionData(evaluationName, groupName, player, testValues, executionDate, comments, playerExecution);
            playerExecution.updated();
            return playerExecution;
        }

        private PlayerExecution playerExecutionData(string evaluationName, string groupName, Player player, ObservableCollection<TestValue> testValues, DateTime executionDate, string comments, PlayerExecution playerExecution)
        {
            try
            {
                playerExecution.EvaluationName = evaluationName;
                playerExecution.GroupName = groupName;
                playerExecution.Player = player;
                playerExecution.Date = executionDate;
                playerExecution.Comments = comments;
                for (int i = 0; i < testValues.Count; i++)
                {
                    playerExecution.addValue(testValues[i]);
                }
                for (int i = 0; i < testValues.Count; i++)
                {
                    if (!testValues[i].Test.Sequence.Equals("n/a"))
                    {
                        testValues[i].ValueExecution = playerExecution.calculateValue(i, testValues[i].Test.Sequence);
                    }
                }
            }
            catch (Exception)
            {
            }
            return playerExecution;
        }

        public TestValue newTestValue(Test test, string value)
        {
            TestValue testValue = new TestValue();
            testValue = testValueData(test, value, testValue);
            return testValue;
        }

        public TestValue updateTestValue(Test test, string value, TestValue testValue)
        {
            testValueData(test, value, testValue);
            testValue.updated();
            return testValue;
        }

        private TestValue testValueData(Test test, string value, TestValue testValue)
        {
            testValue.Test = test;
            if (testValue.Test.Sequence.Equals("n/a"))
            {
                testValue.ValueExecution = float.Parse(value);
            }
            return testValue;
        }

        public ClinicalHistory newClinicalHistory(Player player)
        {
            ClinicalHistory clinicalHistory = new ClinicalHistory();
            clinicalHistory = clinicalHistoryData(player, clinicalHistory);
            return clinicalHistory;
        }

        public ClinicalHistory updateClinicalHistory(Player player, ClinicalHistory clinicalHistory)
        {
            clinicalHistoryData(player, clinicalHistory);
            clinicalHistory.updated();
            return clinicalHistory;
        }

        private ClinicalHistory clinicalHistoryData(Player player, ClinicalHistory clinicalHistory)
        {
            clinicalHistory.Player = player;            
            return clinicalHistory;
        }

        public Disease newDisease(string affectedSystem, string name, string description, int severityPoints, string comment, Boolean ofBirth, DateTime date, string status)
        {
            Disease disease = new Disease();
            disease = diseaseData(affectedSystem, name, description, severityPoints, comment, ofBirth, date, status, disease);
            return disease;
        }

        public Disease updateDisease(string affectedSystem, string name, string description, int severityPoints, string comment, Boolean ofBirth, DateTime date, string status, Disease disease)
        {
            diseaseData(affectedSystem, name, description, severityPoints, comment, ofBirth, date, status, disease);
            disease.updated();
            return disease;
        }

        private Disease diseaseData(string affectedSystem, string name, string description, int severityPoints, string comment, Boolean ofBirth, DateTime date, string status, Disease disease)
        {
            disease.AffectedSystem = affectedSystem;
            disease.Name = name;
            disease.Description = description;
            disease.SeverityPoints = severityPoints;
            disease.Comment = comment;
            disease.OfBirth = ofBirth;
            disease.Date = date;
            disease.Status = status;
            return disease;
        }

        public Injury newInjury(DateTime date, string description, string status, string name, string severity, string affectedArea, string activityWhenInjured, string cause, string treatmentType, string comment)
        {          
            Injury injury = new Injury();
            injury = injuryData(date, description, status, name, severity, affectedArea, activityWhenInjured, cause, treatmentType, comment, injury);
            return injury;
        }

        public Injury updateInjury(DateTime date, string description, string status, string type, string severity, string affectedArea, string activityWhenInjured, string cause, string treatmentType, string comment ,Injury injury)
        {
            injuryData(date, description, status, type, severity, affectedArea, activityWhenInjured, cause, treatmentType, comment, injury);
            injury.updated();
            return injury;
        }

        private Injury injuryData(DateTime date, string description, string status, string name, string severity, string affectedArea, string activityWhenInjured, string cause, string treatmentType, string comment, Injury injury)
        {
            injury.Date = date;
            injury.Description = description;
            injury.Status = status;
            injury.Name = name;
            injury.Severity = severity;
            injury.AffectedArea = affectedArea;
            injury.ActivityWhenInjured = activityWhenInjured;
            injury.Cause = cause;
            injury.TreatmentType = treatmentType;
            injury.Comments = comment;
            return injury;
        }

        public void reflectionGetPersistence(string path)
        {
            path = path + "\\Persistencia.dll";
            Assembly a = Assembly.LoadFrom(path);
            Type[] myTypes = a.GetTypes();
            foreach (Type type in myTypes)
            {
                if (type.Name.Equals("FPersistence"))
                {
                    iPers = (IPersistence)Activator.CreateInstance(type);
                    iPersist = iPers;
                }
            }
            PersistentObject o = new PersistentObject();
            o.LastOID = iPersist.bringLastOID();
        }

        public void calculateValuesOfExecution(PlayerExecution execution)
        {
            for (int i = 0; i < execution.Values.Count; i++)
            {
                execution.Values[i].ValueExecution = execution.calculateValue(i, execution.Values[i].Test.Sequence);
            }
        }

        public void writePlayersExecutionToFile(DateTime date, string evaluationGroupNames, string fileName)
        {
            //fileName = fileName;
            ObservableCollection<PlayerExecution> evaluationExecution = this.loadPlayersExecutionByDate(date, evaluationGroupNames);
            List<string> evaluationInText = new List<string>();
            //cabezal de evaluación
            string line = evaluationGroupNames + ";" + date.ToShortDateString().ToString();
            evaluationInText.Add(line);
            //nombre de columnas
            line = "ID;Nombre;";
            for (int i = 0; i < evaluationExecution[0].Values.Count; i++)
            {
                line = line + evaluationExecution[0].Values[i].Test.Name + ";";
            }
            evaluationInText.Add(line);
            //filas
            for (int i = 0; i < evaluationExecution.Count; i++)
            {
                line = "";
                line = line + evaluationExecution[i].Player.IdentityDocument + ";";
                line = line + evaluationExecution[i].Player.CompleteName + ";";
                for (int j = 0; j < evaluationExecution[i].Values.Count; j++)
                {
                    line = line + evaluationExecution[i].Values[j].ValueExecution + ";";
                }
                evaluationInText.Add(line);
            }
            FilesManager.fileWriter(evaluationInText, fileName);
            openExcelFile(fileName);
        }

        public void writeOnePlayerExecutionsBetweenDates(DateTime begginingDate, DateTime endDate, string playerID, string evaluationName, string fileName)
        {
            ObservableCollection<PlayerExecution> playerExecutionsBetweenDates = this.loadPlayerExecutionsBetweenDates(begginingDate, endDate, playerID, evaluationName);
            List<string> evaluationsInText = new List<string>();
            string line = "Jugador:;" + playerExecutionsBetweenDates[0].Player.CompleteName;
            evaluationsInText.Add(line);
            line = "";
            line = "Evaluación:;" + evaluationName;
            evaluationsInText.Add(line);
            line = "";
            line = "Fecha desde:;" + begginingDate + ";Fecha hasta:;" + endDate;
            evaluationsInText.Add(line);
            line = "";
            for (int i = 0; i < playerExecutionsBetweenDates[0].Values.Count; i++)
            {
                line = line + playerExecutionsBetweenDates[0].Values[i].Test.Name + ";";
            }
            evaluationsInText.Add(line);
            for (int i = 0; i < playerExecutionsBetweenDates.Count; i++)
            {
                line = "";
                for (int j = 0; j < playerExecutionsBetweenDates[i].Values.Count; j++)
                {
                    line = line + playerExecutionsBetweenDates[i].Values[j].ValueExecution + ";";
                }
                evaluationsInText.Add(line);
            }
            FilesManager.fileWriter(evaluationsInText, fileName);
            openExcelFile(fileName);
        }

        public void openExcelFile(string textFileName)
        {
            string filename = "Excel.exe";
            Process proc = new Process();
            proc.EnableRaisingEvents = false;
            proc.StartInfo.FileName = filename;
            proc.StartInfo.Arguments = textFileName.Trim();
            proc.Start();
        }

        public bool readPlayersExecutionFromFile(ObservableCollection<PlayerExecution> executions, string path)
        {
            bool ret = true;
            List<string> executionsAsStrings = FilesManager.fileReader(path);
            string[] names = executionsAsStrings[0].Split(',');
            string evaluationName = names[0].Trim();
            names = names[1].Split(';');
            string[] testNames = executionsAsStrings[1].Split(';');
            if (names.Length >= 3)
            {
                /*try
                { */
                string groupName = names[0].Trim();
                string date = names[1].Trim();
                for (int i = 2; i < executionsAsStrings.Count; i++)
                {
                    string[] values = executionsAsStrings[i].Split(';');
                    string playerId = values[0];
                    for (int j = 0; j < executions.Count; j++)
                    {
                        if (executions[j].Player.IdentityDocument.Equals(playerId) && executions[j].GroupName.Equals(groupName) && executions[j].EvaluationName.Equals(evaluationName))
                        {
                            for (int k = 2; k < values.Length; k++)
                            {
                                for (int l = 0; l < executions[j].Values.Count; l++)
                                {
                                    if (executions[j].Values[l].Test.Name.Equals(testNames[k]))
                                    {
                                        try
                                        {
                                            executions[j].Values[l].ValueExecution = float.Parse(values[k]);
                                        }
                                        catch (Exception)
                                        {

                                        }
                                        l = executions[j].Values.Count;
                                    }
                                }
                            }
                        }
                    }
                }
                //}
                /*catch (Exception)
                {
                    ret = false;
                }*/
            }
            else
            {
                ret = false;
            }
            return ret;
        }

        public ObservableCollection<PlayerExecution> evaluationsOfPlayerByDates(Player player, Evaluation evaluation, DateTime initialDate, DateTime finalDate)
        {
            ObservableCollection<PlayerExecution> executionsByDate = new ObservableCollection<PlayerExecution>();
            for (int i = 0; i < this.PlayersExecutions.Count; i++)
            {
                if (this.PlayersExecutions[i].Player.Equals(player) && this.PlayersExecutions[i].EvaluationName.Equals(evaluation.Name) && initialDate <= this.PlayersExecutions[i].Date && finalDate >= this.PlayersExecutions[i].Date)
                {
                    executionsByDate.Add(this.PlayersExecutions[i]);
                }
            }
            return executionsByDate;
        }


        public ObservableCollection<PlayerExecution> evaluationsOfGroupInADate(Group group, Evaluation evaluation, DateTime date)
        {
            ObservableCollection<PlayerExecution> executionsInADate = new ObservableCollection<PlayerExecution>();
            for (int i = 0; i < this.playersExecutions.Count; i++)
            {
                if (this.PlayersExecutions[i].GroupName.Equals(group.Name) && this.PlayersExecutions[i].EvaluationName.Equals(evaluation.Name) && this.PlayersExecutions[i].Date.Equals(date))
                {
                    executionsInADate.Add(this.PlayersExecutions[i]);
                }
            }
            return executionsInADate;
        }

        public int changeTestPosition(ObservableCollection<Test> testList, int testPosition, bool up)
        {
            int newPosition = testPosition;
            Test testInNewPosition = null;
            if (up)
            {
                if (testPosition != 0)
                {
                    newPosition = (testPosition - 1);
                }
            }
            else
            {
                //if (testPosition != evaluation.Tests.Count - 1)
                if (testPosition < (testList.Count - 1))
                {
                    newPosition = (testPosition + 1);
                }
            }
            /*testInNewPosition = evaluation.Tests[newPosition];
            evaluation.Tests[newPosition] = evaluation.Tests[testPosition];
            evaluation.Tests[testPosition] = testInNewPosition;*/
            testInNewPosition = testList[newPosition];
            testList[newPosition] = testList[testPosition];
            testList[testPosition] = testInNewPosition;
            return newPosition;
        }

        public bool groupWithSameName(string name, int index)
        {
            bool sameName = false;
            for (int i = 0; i < this.Groups.Count; i++)
            {
                if (i != index)
                {
                    if (this.Groups[i].Name.Equals(name))
                    {
                        sameName = true;
                        i = this.Groups.Count;
                    }
                }
            }
            return sameName;
        }


        public bool validateSequence(string sequence, ObservableCollection<Test> tests)
        {
            bool ret = true;
            int sequencerBeggining = 0;
            int sequencerEnd = 0;
            bool oidBeggining = false;
            char previous = ' ';
            for (int i = 0; i < sequence.Length; i++)
            {
                if (sequence[i] == '(')
                {
                    sequencerBeggining++;
                }
                else
                {
                    if (sequence[i] == ')')
                    {
                        sequencerEnd++;
                        if (sequencerEnd > sequencerBeggining)
                        {
                            ret = false;
                            i = sequence.Length;
                        }
                        if (previous == '/' || previous == '*' || previous == '-' || previous == '+' || previous == '^' || previous == '$')
                        {
                            ret = false;
                            i = sequence.Length;
                        }
                    }
                    else
                    {
                        if (sequence[i] == '/' || sequence[i] == '*' || sequence[i] == '-' || sequence[i] == '+' || sequence[i] == '^' || sequence[i] == '$')
                        {
                            if (sequence[i] == '/')
                            {
                                if (i < (sequence.Length - 1))
                                {
                                    if (sequence[i + 1] == '0')
                                    {
                                        if (i < (sequence.Length - 3))
                                        {
                                            if (sequence[i + 2] != ',')
                                            {
                                                ret = false;
                                                i = sequence.Length;
                                            }
                                        }
                                        else 
                                        {
                                            ret = false;
                                            i = sequence.Length;
                                        }
                                    }
                                }
                            }
                            if (ret)
                            {
                                if (i == (sequence.Length - 1))
                                {
                                    ret = false;
                                    i = sequence.Length;
                                }
                                else
                                {
                                    if (i == 0)
                                    {
                                        if (sequence[i] != '-')
                                        {
                                            ret = false;
                                            i = sequence.Length;
                                        }
                                    }
                                    else
                                    {
                                        if (previous == '(')
                                        {
                                            ret = false;
                                            i = sequence.Length;
                                        }
                                        else
                                        {
                                            if (previous == '/' || previous == '*' || previous == '-' || previous == '+' || previous == '^' || previous == '$')
                                            {
                                                ret = false;
                                                i = sequence.Length;
                                            }
                                        }
                                    }
                                }
                            }                            
                        }
                        else
                        {
                            if (sequence[i] == '[')
                            {
                                if (oidBeggining)
                                {
                                    ret = false;
                                    i = sequence.Length;
                                }
                                else
                                {
                                    oidBeggining = true;
                                }
                            }
                            else
                            {
                                if (sequence[i] == ']')
                                {
                                    if (oidBeggining)
                                    {
                                        oidBeggining = false;
                                        int back = 1;
                                        string name = "";
                                        //string numberInChar = "";
                                        //int number = 0;
                                        while (sequence[i - back] != '[')
                                        {
                                            name = sequence[i - back] + name;
                                            //numberInChar = this.Sequence[i - back] + numberInChar;
                                            /*try
                                            {
                                                number = int.Parse(numberInChar);
                                            }
                                            catch (Exception)
                                            {
                                                ret = false;
                                                i = this.Sequence.Length;
                                            }*/
                                            back = back + 1;
                                        }
                                        ret = this.validNameInTests(name, tests);
                                        if (!ret)
                                        {
                                            i = sequence.Length;
                                        }
                                    }
                                    else
                                    {
                                        ret = false;
                                        i = sequence.Length;
                                    }
                                }
                            }
                        }
                    }
                }
                if (i < sequence.Length)
                {
                    previous = sequence[i];
                }
            }
            if (sequencerBeggining != sequencerEnd)
            {
                ret = false;
            }
            return ret;
        }

        public bool validNameInTests(string nameTest, ObservableCollection<Test> tests)
        {
            bool encontre = false;
            for (int i = 0; i < tests.Count; i++)
            {
                if (tests[i].Name.Equals(nameTest))
                {
                    encontre = true;
                    i = tests.Count;
                }
            }
            return encontre;
        }
    }

}
